<!--  -->
<template>
    <!-- component -->
    <div class="bg-transparent h-screen  p-2">
        <div data-tauri-drag-region class="titlebar">
            <div class="absolute top-0 left-3">
                <el-cascader :props="{ label: 'name', value: 'name', children: 'districts' }" v-model="value"
                    :options="options" class="text-black w-32" @change="handleAreaChange"
                    style="background: transparent !important;" />
            </div>

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 rounded-full " id="titlebar-refresh">
                <el-icon>
                    <Refresh />
                </el-icon>
            </div>

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 ml-1 rounded-full" id="titlebar-minimize">
                <el-icon>
                    <Minus />
                </el-icon>
            </div>

            <div class="titlebar-button bg-gradient-to-br from-black to-gray-600 ml-1 rounded-full" id="titlebar-close">
                <el-icon>
                    <Close />
                </el-icon>
            </div>
        </div>
        <div class="bg-transparent p-2 rounded-lg shadow-md max-w-md w-full mt-8">
            <!-- Banner Profile -->
            <div class="relative">
                <el-image :src="this.img" alt="Banner Profile" fit="cover" class="w-full rounded-t-lg h-36"></el-image>
                <div
                    class="absolute bottom-0 left-2/4 transform -translate-x-1/2 translate-y-1/2 flex items-center justify-center w-24 h-24 rounded-full border-4 border-white bg-gradient-to-br from-black to-gray-600">
                    <div class="flex flex-wrap justify-center">
                        <!-- <span class=" text-white" v-if="qweather"> {{ qweather.temperature }}℃</span>
                        <el-divider class="m-0"></el-divider>
                        <span class=" text-white" v-if="qweather"> {{ qweather.feelst }}℃</span> -->

                        <img v-if="qweather" :src="getweathericon(qweather.info)" style="width: 80px;" />
                        <div class="absolute bottom-1" v-if="qweather"> {{ qweather.info }}</div>
                    </div>



                </div>

            </div>
            <!-- User Info with Verified Button -->
            <div class=" items-center mt-0 bg-gradient-to-b from-gray-800 to-black p-2 rounded-md">
                <el-row>
                    <el-col :span="16">
                        <el-badge :value="city" class="item"></el-badge>
                        <el-badge v-if="locality != ''" type="primary" :value="locality" class="item ml-1"></el-badge>
                        <div class="text-white text-left pl-4" style="font-size:0.8rem;font-weight: 800;" v-if="qweather">{{
                            qweather.predict.detail[0].date
                        }}</div>
                    </el-col>

                    <el-col :span="8">
                        <div class=" mt-2  text-transparent bg-gradient-to-r from-pink-500 to-purple-500 bg-clip-text text-center"
                            v-if="qweather" style="font-size: 1.8rem;text-shadow: 2px 2px 4px rgba(255,255,255,0.75);">{{
                                qweather.temperature }}℃

                        </div>


                    </el-col>
                </el-row>
            </div>

            <!-- Social Links -->
            <div class=" items-center mt-4 space-x-4 bg-white text-black rounded-md" v-if="qweather">
                <el-row>
                    <el-col :span="6">
                        <img :src="u2(1)" />
                        <el-divider style="margin: 0px;" />
                        <div class="text-center p-2" v-if="qweather">{{ qweather.rain }}mm</div>
                    </el-col>
                    <el-col :span="6">
                        <img :src="u2(2)" />
                        <el-divider style="margin: 0px;" />
                        <div class="text-center p-2" v-if="qweather">
                            <el-badge :value="qweather.power" class="item" type="primary">
                                {{ qweather.data.real.wind.direct }}

                            </el-badge>
                        </div>
                    </el-col>
                    <el-col :span="6">
                        <img :src="u2(3)" />
                        <el-divider style="margin: 0px;" />
                        <div class="text-center p-2" v-if="qweather">{{ qweather.data.real.weather.humidity }}%</div>
                    </el-col>
                    <el-col :span="6">
                        <img :src="u2(4)" />
                        <el-divider style="margin: 0px;" />
                        <div class="text-center p-2" v-if="qweather">{{ qweather.feelst }}℃</div>
                    </el-col>
                </el-row>
            </div>

            <div class="p-2 flex justify-between bg-gradient-to-b from-gray-800 to-gray-600">

                <swiper v-if="qweather" :slides-per-view="3" :space-between="50" @swiper="onSwiper"
                    @slideChange="onSlideChange" :options="swiperOption">
                    <swiper-slide v-for="(     w, index     ) in       qweather.predict.detail      " :key="index">
                        <div class="text-white pt-6 whitespace-nowrap" style="width:100%;text-align: center;">

                            {{
                                w.date.split("-")[1] + "月" + w.date.split("-")[2] + "日" }}

                        </div>
                        <div class="text-white" style="width:100%;text-align: center;">
                            <el-badge :value="getweek(w.date)" class="p-2"></el-badge>

                        </div>
                        <!-- <img style="margin: 0 auto;"
:src="'http://image.nmc.cn/assets/img/w/40x40/4/' + w.day.weather.img + '.png'" /> -->
                        <div class="text-white pt-2" style="width:100%;text-align: center;">
                            <el-tooltip :content="w.day.weather.info" placement="bottom">
                                <img :src="getweathericon(w.day.weather.info)" />
                            </el-tooltip>
                        </div>
                        <div class="text-white pt-2" style="width:100%;text-align: center;">{{
                            w.day.wind.direct == "9999" ? "-" : w.day.wind.direct }}</div>
                        <div class="text-white" style="width:100%;text-align: center;">{{
                            w.day.wind.power == "9999" ? "-" : w.day.wind.power }}</div>
                        <div class="text-white pt-2 pb-2 border border-1 border-dashed rounded-md"
                            style="width:100%;text-align: center;" :class="backgroundStyle(w.day.weather.temperature)">
                            {{
                                w.day.weather.temperature == 9999 ? "-" : w.day.weather.temperature + '℃' }}</div>
                        <div class="text-white pt-2 pb-2 border border-1 border-dashed rounded-md mt-1"
                            style="width:100%;text-align: center;" :class="backgroundStyle(w.night.weather.temperature)">
                            {{
                                w.night.weather.temperature == 9999 ? "-" : w.night.weather.temperature + '℃' }}</div>
                        <!-- <img style="margin: 0 auto;"
:src="'http://image.nmc.cn/assets/img/w/40x40/4/' + w.night.weather.img + '.png'" /> -->
                        <div class="text-white pt-2" style="width:100%;text-align: center;">{{
}}
                            <el-tooltip :content="w.night.weather.info" placement="bottom">
                                <img :src="getweathericon(w.night.weather.info)" />
                            </el-tooltip>
                        </div>
                        <div class="text-white pt-2" style="width:100%;text-align: center;">{{
                            w.night.wind.direct == "9999" ? "-" : w.night.wind.direct }}</div>
                        <div class="text-white pt-2 pb-2" style="width:100%;text-align: center;">{{
                            w.night.wind.power == "9999" ? "-" : w.night.wind.power }}</div>

                    </swiper-slide>

                </swiper>

            </div>
        </div>
    </div>
</template>

<script>
import { appWindow, WebviewWindow } from "@tauri-apps/api/window";
import { emit, listen } from '@tauri-apps/api/event'
import { getClient, ResponseType } from '@tauri-apps/api/http';

// Import Swiper Vue.js components
import { Swiper, SwiperSlide } from 'swiper/vue';
import { districtsOpt } from '../districts.js';
// 引入swiper样式（按需导入）
import 'swiper/css/pagination' // 轮播图底面的小圆点
import 'swiper/css/navigation' // 轮播图两边的左右箭头
// Import Swiper styles
import 'swiper/css';



export default {
    data() {
        return {
            img: "",
            qweather: null,
            city: "",
            locality: "",
            weatherUpdateTimer: null,
            value: "",
            options: districtsOpt,
            swiperOption: {
                direction: "horizontal",
                pagination: {
                    el: '.swiper-pagination',
                    clickable: true, // 分页器可以点击
                },
                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },
                scrollbar: true
            },
            windurl: ""

        };
    },

    components: {

        Swiper,
        SwiperSlide,
    },


    computed: {},

    mounted() {
        this.getUserLocation();
        document
            .getElementById("titlebar-refresh")
            .addEventListener("click", () => window.location.reload());
        document
            .getElementById("titlebar-minimize")
            .addEventListener("click", () => appWindow.minimize());

        document
            .getElementById("titlebar-close")
            .addEventListener("click", () => appWindow.close());
    },

    created() { },

    methods: {
        u2(type) {
            if (type == 1) {

                return new URL('../assets/svg/rain.svg', import.meta.url).href
            }
            else if (type == 2) {

                return new URL('../assets/svg/dust-wind.svg', import.meta.url).href
            }
            else if (type == 3) {

                return new URL('../assets/svg/raindrops.svg', import.meta.url).href
            }
            else if (type == 4) {

                return new URL('../assets/svg/thermometer-celsius.svg', import.meta.url).href
            }
        },
        u(url) {

            return new URL(url, import.meta.url).href
        },
        s(power) {
            setTimeout(() => {
                let url = '../assets/svg/wind-beaufort-' + power.replace('级', '').replace('微风', '0') + '.svg';
                console.log(power, url)
                return new URL(url, import.meta.url).href;
            }, 1000);

        },
        getweathericon(type) {
            if (type == "晴") {

                return new URL("../assets/svg/clear-day.svg", import.meta.url).href
            }
            else if (type == "多云") {
                return new URL("../assets/svg/cloudy.svg", import.meta.url).href;
            }
            else if (type == "阴") {
                return new URL("../assets/svg/clear-night.svg", import.meta.url).href;
            }
            else if (type.indexOf("雨") > -1) {
                return new URL("../assets/svg/partly-cloudy-day-rain.svg", import.meta.url).href;
            }
            else if (type.indexOf("雪") > -1) {
                return new URL("../assets/svg/snow.svg", import.meta.url).href;
            }
            else {
                return new URL("../assets/svg/not-available.svg", import.meta.url).href;
            }
        },
        getweek(d) {
            const weekDays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            const date = new Date(d);
            return weekDays[date.getDay()];
        },
        backgroundStyle(value) {
            if (value != 9999) {
                if (value <= -15) {
                    return 'bg-red-500';
                } else if (value < 0 && value > -15) {
                    return 'bg-blue-500';
                } else if (value >= 0 && value < 10) {
                    return 'bg-green-500';
                } else {
                    return 'bg-yellow-500';
                }
            }
        },
        getCityPic(city) {
            // const client = createClient(import.meta.env.VITE_pexels_api_key);
            // const query = "中国" + city;
            // client.photos.search({ query, per_page: 12, locale: 'zh-CN' }).then(photos => {
            //     console.log(photos);
            //     this.img = photos.photos[9].src.medium;
            //     console.log('this.img', this.img)
            // });
            this.img = "https://zt-1304966785.cos.ap-nanjing.myqcloud.com/" + city + ".png";
        },
        scheduleGetUserLocation() {
            const now = new Date();
            const nextHour = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours() + 1, 0, 1, 0);
            const delay = nextHour - now;

            setTimeout(() => {
                this.getUserLocation();
                this.weatherUpdateTimer = setInterval(this.getUserLocation.bind(this), 1000 * 60 * 60);
            }, delay);
        },
        getUserLocation() {
            console.log("getUserLocation")
            if (navigator.geolocation) {
                console.log("getUserLocation")
                navigator.geolocation.getCurrentPosition(this.getCityFromCoordinates, this.handleLocationError);
            } else {
                console.log("Geolocation is not supported by this browser.");
            }
        },
        async handleAreaChange(value) {
            this.city = value[1];
            this.locality = '';
            console.log('this.city', this.city)
            const client = await getClient();
            const response = await client.get("https://zhangteng.cloud/5001//api/Rss/GetWeather", {
                timeout: 30,
                query: {
                    cityName: this.city.replace('市', ''),
                },
                // the expected response type
                responseType: ResponseType.JSON
            });

            this.qweather = response.data;
            console.log('response', this.qweather)
            this.qweather.temperature = this.qweather.data.real.weather.temperature;
            this.qweather.feelst = this.qweather.data.real.weather.feelst;
            this.qweather.info = this.qweather.data.real.weather.info;
            this.qweather.direct = this.qweather.data.real.wind.direct;
            this.qweather.speed = this.qweather.data.real.wind.speed;
            this.qweather.power = this.qweather.data.real.wind.power;
            this.qweather.rain = this.qweather.data.real.weather.rain;
            this.qweather.humidity = this.qweather.data.real.weather.humidity;
            this.qweather.predict = this.qweather.data.predict;



        },
        async getCityFromCoordinates(position) {
            console.log("getCityFromCoordinates")
            const lat = position.coords.latitude;
            const lon = position.coords.longitude;
            const client = await getClient();
            const response = await client.get(`https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=zh`, {
                timeout: 30,

                // the expected response type
                responseType: ResponseType.JSON
            });
            console.log('response', response)
            const data = await response.data;
            const city = data.city;
            this.city = city;

            this.locality = data.locality;
            this.getCityPic(data.city);
            console.log(city)
            try {

                const client = await getClient();
                const response = await client.get('https://zhangteng.cloud/5001/api/Rss/GetWeather', {
                    timeout: 30,
                    query: {
                        cityName: city.replace('市', ''),
                    },
                    // the expected response type
                    responseType: ResponseType.JSON
                });
                console.log("GetWeather", response.data)
                this.qweather = response.data;
                this.qweather.city = city;
                this.qweather.temperature = this.qweather.data.real.weather.temperature;
                this.qweather.feelst = this.qweather.data.real.weather.feelst;
                this.qweather.info = this.qweather.data.real.weather.info;
                this.qweather.direct = this.qweather.data.real.wind.direct;
                this.qweather.speed = this.qweather.data.real.wind.speed;
                this.qweather.power = this.qweather.data.real.wind.power;


                this.qweather.rain = this.qweather.data.real.weather.rain;
                this.qweather.humidity = this.qweather.data.real.weather.humidity;
                this.qweather.predict = this.qweather.data.predict;
                console.log(this.qweather)
                // get("/api/Rss/GetWeather", { cityName: city.replace('市', '') }).then((res) => {
                //     console.log(res)
                //     this.qweather = res;
                //     this.qweather.city = city;
                //     this.qweather.temperature = this.qweather.data.real.weather.temperature;
                //     this.qweather.feelst = this.qweather.data.real.weather.feelst;
                //     this.qweather.info = this.qweather.data.real.weather.info;
                //     this.qweather.direct = this.qweather.data.real.wind.direct;
                //     this.qweather.speed = this.qweather.data.real.wind.speed;
                //     this.qweather.power = this.qweather.data.real.wind.power;
                //     this.qweather.rain = this.qweather.data.real.weather.rain;
                //     this.qweather.humidity = this.qweather.data.real.weather.humidity;
                //     this.qweather.predict = this.qweather.data.predict;
                //     console.log(this.qweather)

                // }).catch(error => {
                //     // 错误处理逻辑
                //     //window.$message.warning(error);
                // });


            } catch (error) {
                // window.$message.warning(error);
            }
        },
    }
}

</script>
<style lang='scss' scoped></style>